<template>
  <el-dialog v-model="visible" :align-center="true" title="导入数据" width="600px" @close="handleClose">
    <el-scrollbar max-height="60vh">
      <el-form
        ref="importFormRef"
        label-width="auto"
        style="padding-right: var(--el-dialog-padding-primary)"
        :model="importFormData"
        :rules="importFormRules"
      >
        <el-form-item label="文件名" prop="files">
          <el-upload
            ref="uploadRef"
            v-model:file-list="importFormData.files"
            class="w-full"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            drag
            :limit="1"
            :auto-upload="false"
            :on-exceed="handleFileExceed"
          >
            <el-icon class="el-icon--upload"><ep-UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                格式为*.xlsx / *.xls，文件不超过一个
                <el-link v-if="templateAction" type="primary" :underline="false" @click="handleDownloadTemplate">
                  下载模板
                  <el-icon class="el-icon--right"><ep-Download /></el-icon>
                </el-link>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div style="padding-right: var(--el-dialog-padding-primary)">
        <el-button :loading="loading" type="primary" :disabled="importFormData.files.length === 0" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useRequest } from '@/hooks/useRequest'
import { upload } from '@/service/request'
import { genFileId } from 'element-plus'
import type { FormInstance, UploadInstance, UploadUserFile, FormRules, UploadRawFile } from 'element-plus'

const visible = defineModel<boolean>({ default: false })

const props = defineProps<{
  action?: string // 上传文件 URL
  templateAction?: string // 下载模板请求URL
}>()

const emit = defineEmits(['import-success'])

const importFormRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()

const { loading, runAsync } = useRequest(upload, { manual: true })

const importFormData = reactive<{
  files: UploadUserFile[]
}>({
  files: []
})

const importFormRules: FormRules = {
  files: [{ required: true }]
}

function handleClose() {
  visible.value = false
  importFormRef.value?.resetFields()
}

function handleFileExceed(files: File[]) {
  // 覆盖前一个文件
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

async function handleSubmit() {
  if (!props.action) {
    ElMessage.error('未配置文件上传的URL')
    return
  }
  if (!importFormData.files.length) {
    ElMessage.warning('请选择文件')
    return
  }
  try {
    await runAsync(props.action, { file: importFormData.files[0].raw as File })
    ElMessage.success('导入成功')
    emit('import-success')
    handleClose()
  } catch {
    /* empty */
  }
}

function handleDownloadTemplate() {
  if (props.templateAction) {
    saveXlsx()
  }
}

function saveXlsx(fileName?: string) {
  const downloadLink = document.createElement('a')

  const downloadUrl = import.meta.env.VITE_APP_BASE_API + props.templateAction
  downloadLink.href = downloadUrl
  downloadLink.download = fileName

  document.body.appendChild(downloadLink)
  downloadLink.click()

  document.body.removeChild(downloadLink)
}
</script>
<style lang="scss" scoped></style>
